package com.xiaozeng.search.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaozeng.clients.ProductClient;
import com.xiaozeng.pojo.Product;
import com.xiaozeng.pojo.ProductDoc;
import lombok.extern.slf4j.Slf4j;



import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.xiaozeng.constants.SearchConstants.CREATE_INEX;

/**
 * @Author: xiaozeng
 * @Date: 2022 11
 * @Description: 监控程序启动,初始化es数据
 **/
@Component
@Slf4j
public class ApplicationRunListener implements ApplicationRunner {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ProductClient productClient;


    /**
     * 当search服务运行时，就会启动这个程序，把mysql里的数据同步到ES数据库中
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {

        //判断是否存在product索引
        GetIndexRequest getIndexRequest = new GetIndexRequest("product");
        boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);


        if (!exists){
            //不存在,创建新索引
            CreateIndexRequest createIndexRequest = new CreateIndexRequest("product");
            //用JSON格式读入CREATE_INEX里的代码作为索引命令
            createIndexRequest.source(CREATE_INEX, XContentType.JSON);
            CreateIndexResponse response =
                    restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
            System.out.println("创建索引的响应"+response);
        }

        //删除全部数据
        DeleteByQueryRequest deleteIndexRequest = new DeleteByQueryRequest("product");
        deleteIndexRequest.setQuery(QueryBuilders.matchAllQuery());//匹配全部删除
        restHighLevelClient.deleteByQuery(deleteIndexRequest,RequestOptions.DEFAULT);

        //查询全部数据
        List<Product> list = productClient.list();

        //插入全部数据
        //批量插入，单条插入使用IndexRequest
        BulkRequest bulkRequest = new BulkRequest();
        ObjectMapper objectMapper = new ObjectMapper();
        for (Product product : list) {
            ProductDoc productDoc = new ProductDoc(product);

            bulkRequest.add(new IndexRequest("product")
                    .id(productDoc.getProductId().toString())
                    .source(objectMapper.writeValueAsString(productDoc),XContentType.JSON));
        }

        restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);

        log.info("ApplicationRunListener.run业务结束，完成数据更新!");

    }

}
